//
// Created by 刘会 on 2018/12/18.
//


#include "opencv_jni.h"


JNIEXPORT jstring nativeI420ToRGB(JNIEnv *env, jclass type, jbyteArray src_,
                                     jint width, jint height) {
    jbyte *src = env->GetByteArrayElements(src_, NULL);
    Mat I420(height * 3 >> 1, width, CV_8UC1);
    I420.data = reinterpret_cast<uchar *>(src);
    InputArray mInputArray(I420);
    Mat rgb(width, height, CV_8UC3);
    OutputArray mOutputArray(rgb);
    cvtColor(mInputArray, mOutputArray, COLOR_YUV2BGR_I420, 0);
    const char *filename = "/sdcard/111/t.jpg";
    bool b = imwrite(filename,mOutputArray);
    LOGE("图片写入结果：b=%d,路径=%s",b,filename);

    if (src) {
        env->ReleaseByteArrayElements(src_, src, 0);
    }
    if(b){
//        Mat des = imread(filename);
        LOGI("rows,cols,channels = %d,%d,%d",rgb.rows,rgb.cols,rgb.channels());
//        size_t length = rgb.rows * rgb.cols * rgb.channels();
//        jbyteArray jbyteArray1 = env->NewByteArray(length);
//        env->SetByteArrayRegion(jbyteArray1, 0, length, reinterpret_cast<const jbyte *>(rgb.data));
        return env->NewStringUTF(filename);
    }
    return nullptr;


}


static JNINativeMethod methods[] = {
        {"nativeI420ToRGB", "([BII)Ljava/lang/String;", (void *) nativeI420ToRGB},

};

jint registerNativeMethods(JNIEnv *env, const char *class_name, JNINativeMethod *methods,
                           int num_methods) {
    int result = 0;

    jclass clazz = env->FindClass(class_name);
    if (LIKELY(clazz)) {
        int result = env->RegisterNatives(clazz, methods, num_methods);
        if (UNLIKELY(result < 0)) {
            LOGE("registerNativeMethods failed(class=%s)", class_name);
        }
    } else {
        LOGE("registerNativeMethods: class'%s' not found", class_name);
    }
    return result;
}


int register_method(JNIEnv *env) {
    LOGV("register_libopencv_jni:");
    if (registerNativeMethods(env,
                              "com/media/yuvplayer/utils/OpenCVUtils",
                              methods, NUM_ARRAY_ELEMENTS(methods)) < 0) {
        return -1;
    }
    return 0;
}

